from PyQt4.QtCore import QEventLoop, SIGNAL

import urllib
import urllib2
import cookielib
import json

import config


class BaseDriver(QEventLoop):
    def __init__(self, parent=None):
        super(BaseDriver, self).__init__(parent)
        self.opener = None
        self.cookiejar = None
        self.initOpener()

    def initOpener(self):
        self.cookiejar = cookielib.CookieJar()
        self.opener = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(self.cookiejar)
        )

    def get_csrf_token(self):
        for cookie in self.cookiejar:
            if cookie.name == 'csrftoken':
                return cookie.value
        return None

    def doRequest(self, action, values):
        data = urllib.urlencode(values)
        request = urllib2.Request(config.SERVER + action, data)
        response_str = self.opener.open(request).read()
        response = json.loads(response_str)
        return response